package demo2;

import demo1.UdpEchoClient;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-08-08
 * Time: 10:31
 */
public class UdpEchoClient2 {
    private DatagramSocket udpEchoClient2 = null;
    private String server2Ip = null;
    private int port = 0;

    public UdpEchoClient2(String server2Ip, int port) throws SocketException {
        this.server2Ip = server2Ip;
        this.port = port;
        udpEchoClient2 = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.print("-> ");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(server2Ip), port);
            udpEchoClient2.send(requestPacket);

            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            udpEchoClient2.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient2 client = new UdpEchoClient2("127.0.0.1", 9090);
        client.start();
    }

}
